package com.lonefennec.chameleon;

import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;

public class TilingBackground extends Actor
{
	private Texture texture;
	
	public float speedFactor = 1.0f;
	
	@Override
	public void draw(SpriteBatch batch, float parentAlpha)
	{
		int tileWidth = texture.getWidth();
		int tileHeight = texture.getHeight();
		
		int stageWidth = (int) stage.width();
		int stageHeight = (int) stage.height();
		
		int tilesX = (int) ((stageWidth / tileWidth) + 1);
		int tilesY = (int) ((stageHeight / tileHeight) + 1);
		
		/*
		 * it's simpler to do this all in screen coords then convert it, but the
		 * camera is in world coords so convert here
		 */
		int camX = (int) (Physics.WORLD_TO_SCREEN * stage.getCamera().position.x);
		int camY = (int) (Physics.WORLD_TO_SCREEN * stage.getCamera().position.y);
		
		camX = (int) (camX * speedFactor);
		
		int startX = camX - stageWidth / 2;
		int startY = camY - stageHeight / 2;
		
		startX -= startX % tileWidth;
		startY -= startY % tileHeight;
		
		/*
		 * so far we have worked out the amount of tiles that actually fit on
		 * the screen - the -1 and +1 here come from the fact that we want an
		 * extra part tile on each edge
		 */
		for (int xIt = -2; xIt < tilesX + 2; ++xIt)
		{
			for (int yIt = -2; yIt < tilesY + 2; ++yIt)
			{
				float drawX = Physics.SCREEN_TO_WORLD * (startX + xIt * tileWidth);
				float drawY = Physics.SCREEN_TO_WORLD * (startY + yIt * tileHeight);
				
				batch.draw(texture, drawX, drawY, tileWidth * Physics.SCREEN_TO_WORLD, tileHeight * Physics.SCREEN_TO_WORLD);
			}
		}
	}
	
	@Override
	public Actor hit(float x, float y)
	{
		return null;
	}
	
	public TilingBackground(AssetManager assets, String texturePath)
	{
		assets.load(texturePath, Texture.class);
		assets.finishLoading();
		
		texture = assets.get(texturePath, Texture.class);
	}
}
